//导入模块
const fs = require("fs");
const path = require("path");
const router = require("koa-router")();

function search(contropath) {

    let files = fs.readdirSync(contropath);
    console.log(files);

    let file = files.filter((element) => {
        return element.endsWith("js") && element !== "index.js"
    })

    return file;


}



function fen(file, contropath) {
    file.forEach(item => {
        let tmpPath = path.join(contropath, item);
        console.log(tmpPath);
        let routerObj = require(tmpPath);
        console.log(routerObj);
        // 循环定义路由及对应的处理函数
        for (let r in routerObj) {
            console.log(r);
            // 获取路由定义的类型，是get请求还post请求，分别调用不同的函数来调用
            let type = routerObj[r][0];
            // 获取路由定义中的请求后要调用的函数
            let fn = routerObj[r][1];
            console.log(fn);
            if (type === 'get') {
                router.get(r, fn);
            } else {
                router.post(r, fn);
            }
        }
    })


}



module.exports = function () {

    let contropath = (__dirname);
    console.log(contropath);

    let file = search(contropath);

    fen(file, contropath);

    return router.routes();

};